<template>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" class="elDiaLog" lock-scroll
		width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">

		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading2">
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="180px">
				<el-form-item label="资产名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入资产名称" />
				</el-form-item>
				<el-form-item label="所属公司" prop="cid">
					<el-tree-select 
						placeholder="请选择所属公司" 
						v-model="formData.cid"
						:data="baseConfigStore.newExCompanyList" 
						:render-after-expand="false" 
						:default-expand-all="true"
						check-strictly >
							<template v-slot:default="{ node,data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select >
				</el-form-item>
				<el-form-item label="权属单位" prop="affiliated_unit">
					<el-tree-select 
						placeholder="请选择权属单位" 
						v-model="formData.affiliated_unit"
						:data="baseConfigStore.newExCompanyList" 
						:render-after-expand="false" 
						:default-expand-all="true"
						check-strictly >
							<template v-slot:default="{ node,data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select >
				</el-form-item>
				<el-form-item label="所属类目" prop="class_id">
					<el-tree-select :disabled="formData.id?true:false" v-model="formData.class_id" placeholder="选择所属类目"
						:data="menuOptions" :props="{label:'class_name',children: 'children',value: 'id'}"
							 filterable check-strictly :render-after-expand="false" @node-click="nodeClick" />
				</el-form-item>
				
				
				
				<el-form-item v-if="otherList.length>0" v-for="(item,index) in otherList" :key="item.id"
					:label="item.name" :prop="item.field">
					<!-- 文本内容 -->
					<template v-if="item.type=='text'">
						<!-- 日期+时间 -->
						<el-date-picker v-if="item.input_type=='datetime'" v-model="formData[item.field]"
							type="datetime" format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss"
							:placeholder="`请输入${item.name}`" />
						 <!-- 起止日期 -->
						  <el-date-picker
								v-else-if="item.input_type=='startimeEndtime'"
						        v-model="formData[item.field]"
						        type="daterange"
						        range-separator="到"
						        start-placeholder="开始日期"
						        end-placeholder="结束日期"
								 format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
						<!-- 日期 -->
						<el-date-picker v-else-if="item.input_type=='date'" v-model="formData[item.field]" type="date"
							format="YYYY-MM-DD" value-format="YYYY-MM-DD" :placeholder="`请选择${item.name}`" />
						<!-- 时间 -->
						<el-time-picker v-else-if="item.input_type=='time'" v-model="formData[item.field]"
							format="hh:mm:ss" value-format="hh:mm:ss" :placeholder="`请选择${item.name}`" />
						<el-input v-else="item.input_type=='datetime'" :type="item.input_type"
							v-model="formData[item.field]" :placeholder="`请输入${item.name}`" />
					</template>
					<!-- 多行文本框 -->
					<el-input v-else-if="item.type=='textarea'" type="textarea" rows="4" v-model="formData[item.field]"
						resize="none" :placeholder="`请输入${item.name}`" />
					<!-- 单选框 -->
					<el-radio-group v-else-if="item.type=='radio'" v-model="formData[item.field]">
						<el-radio v-for="(ite,ind) in changeData(item.parameter)" :value="ite">{{ite}}</el-radio>
					</el-radio-group>
					<!-- 多选框 -->
					<el-checkbox-group v-else-if="item.type=='checkbox'" v-model="formData[item.field]">
						<el-checkbox v-for="(ite,index) in changeData(item.parameter)" :label="ite" :value="ite" />
					</el-checkbox-group>
					<!-- 下拉选择 -->
					<el-select v-else-if="item.type=='select'" v-model="formData[item.field]"
						:placeholder="`请选择${item.name}`">
						<el-option v-for="(ite,ind) in changeData(item.parameter)" :key="ite" :label="ite"
							:value="ite" />
					</el-select>
					<!-- 开关按钮 -->
					<el-switch v-else-if="item.type=='switch'" v-model="formData[item.field]" />
					<!-- 文件上传 -->
					<template v-else-if="item.type=='file'">
						<el-upload style="width: 100%;" v-if="item.upload_type=='image'"
							v-model:file-list="formData[item.field]" 
							action="/api/upload" 
							list-type="picture-card"
							:on-preview="onImgPreview" 
							:before-upload="imageBeforUpload" 
							:on-success="(response:any, file:any, fileList:any) => {
							  return imageBeforUploadSuccess(response, file, fileList,item.field);
							}" :multiple="false" :limit="item.multiple == 0 ?1:6">
							<i-ep-plus />
							<template #tip>
								<div class="el-upload__tip">
									<el-text size="small" type="info">{{imageType.pageShow}} </el-text>
								</div>
							</template>
						</el-upload>
						<el-upload style="width: 100%;" v-else-if="item.upload_type=='file'"
							v-model:file-list="formData[item.field]"
							 action="/api/upload" 
							:multiple="false"
							:on-preview="onFilePreview" :before-upload="FileBeforUpload" :on-success="(response:any, file:any, fileList:any) => {
							  return imageBeforUploadSuccess(response, file, fileList,item.field);
							}" :limit="item.multiple == 0 ?1:6">
							<el-button type="primary">文件上传</el-button>
							<template #tip>
								<div class="el-upload__tip">
									<el-text size="small" type="info">{{feilType.pageShow}}</el-text>
								</div>
							</template>
						</el-upload>
					</template>

				</el-form-item>
			</el-form>
		
		</div>
		<div class="form-box" v-if="['act_info'].includes(dialogStatus)" v-loading="loading2">
		
			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1"
					label="操作人：">
					<span>{{ dataInfo.user?.name }}</span>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="资产名称：">
					<span>{{ dataInfo.name }}</span>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="所属公司：">
					<span>{{ dataInfo.company?.name }}</span>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="权属单位：">
					<span>{{ dataInfo.unit_info?.name }}</span>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="所属类目：">
					<span>{{ dataInfo.class_info?.class_name }}</span>
				</el-descriptions-item>
				<el-descriptions-item
					v-for="(item,index) in otherList"
					label-class-name="labelC1"
					:label="item.name">
					<div class="item" v-if="item.upload_type=='image' && item.type=='file'">
						<el-image 
							v-if="formData[item.field]?.length >0" 
							v-for="(ite, ind) in formData[item.field]"
						    style="width: 100px; height: 100px;margin-right: 10px;" 
							:src="ite.url"
						    :zoom-rate="1.2" 
							:max-scale="7" 
							:min-scale="0.2"
						    :preview-src-list="imglist(formData[item.field])" 
							:initial-index="ind" 
							fit="cover" /> 
							<el-text v-else type="info">无</el-text>
					</div>
					<div class="item" v-else-if="item.upload_type=='file' && item.type=='file'">
						<div v-if="formData[item.field]?.length >0"
							v-for="(ite,ind) in formData[item.field]">
							<el-link @click="onFilePreview(ite)" type="primary">{{ind + 1}}.{{ite.name}}</el-link>
						</div>
						<el-text v-else type="info">无</el-text>
					</div>
					<span v-else>
						<span v-if="item.field.includes('SETIME') && formData[item.field]">
							{{formData[item.field][0]}} 到 {{formData[item.field][1] }}
						</span>
						<span v-else-if="formData[item.field]"  type="info">{{ formData[item.field] }}</span>
						<el-text v-else type="info">无</el-text>
					</span>
				</el-descriptions-item>
				
			</el-descriptions>	
		</div>
		<div class="form-box" v-if="['Udetail'].includes(dialogStatus)" v-loading="loading2">
			外部查看详情信息
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info','Udetail'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" type="primary" :loading="loading3"
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'重新提交':'确 定'}}</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">取 消</el-button>
			</div>
		</template>
	</el-dialog>

</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { imageType, feilType} from "@/utils/funcall";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import { BUSINESS_TYPE } from "@/utils/constant";
	import Editor from "@/components/WangEditor/index.vue";

	//接口地址
	import {
		getAssetClass,
		getAssetAdd,
		getAssetDetail,
		getAssetEidt,
		getAssetOptions
	} from "@/api/asset";

	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		}
	});

	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading2 = ref(false);//新增或者修改加载load按钮
	const loading3 = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref

	const dataFormRef = ref(ElForm);
	const dataInfo = ref<any>({});
	const formData = ref<any>({
		id: undefined,
		cid: "",//所属公司
		class_id: "",//所属类目
		name: "",//标题
		affiliated_unit:"",//权属单位
	})
	const rules = reactive<any>({
		cid: [{ required: true, message: "请选择所属公司", trigger: "change" }],
		class_id: [{ required: true, message: "请选择类目", trigger: "change" }],
		name: [{ required: true, message: "请填写标题", trigger: "change" }]
	})
	const detail = ref();

	watch(
		() => props.dialogTableValue,
		() => {
			if (props.dialogStatus == "audit_art") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_info") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_edit") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "Udetail") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
				console.log('添加信息')
			}
		}, { deep: true, immediate: true })

	// users: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
	// 提交新增内容/or修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			console.log(valid)
			if (valid) {
				loading3.value = true;

				if (formData.value.id) {
					ElMessageBox.confirm("是否要修改信息?", "警告", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(() => {
						getAssetEidt(formData.value).then((res) => {
							console.log(res)
							emit('initRefreshList');
							loading3.value = false;
							ElMessage({ message: '修改成功', type: 'success', duration: 1000 })
							closeDialog();
						}).finally(() => {
							loading3.value = false;
						})
					}).catch(() => {
						loading3.value = false;
					});
				}
				else {
					getAssetAdd(formData.value).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '添加成功', type: 'success', duration: 1000 })
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
			}
		});
	}



	// 关闭弹窗
	function closeDialog() {
		if (!loading3.value) {
			emit('update:modelValue', false)
		}
	}

	// 获取详情
	function getAuditDetail(row) {
		console.log(row)
		loading2.value = true;
		getAssetDetail({ id: row.id }).then((res) => {

			let data = res.data;
			formData.value.id = data.id;
			formData.value.cid = data.cid;
			formData.value.class_id = data.class_id;
			formData.value.name = data.name;
			formData.value.affiliated_unit = data.affiliated_unit;

			dataInfo.value = res.data;

			detail.value = res.data.detail
			getPositionList(data.class_id);


		}).finally(() => {
			loading2.value = false;
		})
	}

	//获取类目列表
	const menuOptions = ref<any>([]);
	function initLeiMu() {
		getAssetClass({}).then((res) => {
			menuOptions.value = res.data;
		}).finally(() => { })
	}

	//获取类目详情
	const otherList = ref<any>([]);

	function getPositionList(class_id : any) {
		var newdata : any = {
			id: formData.value.id,
			cid: formData.value.cid,
			class_id: class_id,
			name: formData.value.name,
			affiliated_unit:formData.value.affiliated_unit,//权属单位
		}
		loading2.value = true;
		getAssetOptions({
			id: class_id
		}).then((res) => {
			for (var i = 0; i < res.data.length; i++) {
				var newItem = res.data[i];
				if (formData.value.id) {

					newdata[newItem.field] = detail.value[newItem.field];
				}
				else {
					if (newItem.type == "checkbox" || newItem.type == "file") {
						newdata[newItem.field] = [];
					}
					else if (newItem.type == "switch") {
						newdata[newItem.field] = false;
					}
					else {
						newdata[newItem.field] = "";
					}
				}
			}

			formData.value = newdata;
			otherList.value = res.data;

		}).finally(() => {
			loading2.value = false;
		})
	}

	function nodeClick(a : any, b : any, c : any, d : any) {
		// queryParams.cid = a.cid;
		console.log(a)
		getPositionList(a.id);
	}
	function changeData(arr) {
		// 给定的数据字符串
		// 将数据字符串按换行符拆分成数组
		var dataArray = arr.split("\n");
		// 定义一个空数组用于存储结果
		var resultArray = [];
		// 遍历数据数组
		for (var i = 0; i < dataArray.length; i++) {
			// 将每一行数据按"=>"拆分成键和值，并添加到结果数组中
			var keyValue = dataArray[i].split("=>");
			// 如果拆分后的数组长度为2，则说明是键值对，否则跳过
			if (keyValue.length === 2) {
				resultArray[parseInt(keyValue[0]) - 1] = keyValue[1];
			}
		}
		return resultArray;
	}

	// 预览图片
	const ylImg = ref({
		visible: false,
		info: ""
	})
	function onImgPreview(file : any) {
		console.log(file)
		ylImg.value.visible = true;
		ylImg.value.info = file
	}
	// 文件上传
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < imageType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (imageType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: imageType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: imageType.prompt,
				type: 'error',
			})
			return false;
		}
	}
	// 文件预览 --点击下载
	function onFilePreview(file:any) {
		if (file.status == "success") {
			const a = document.createElement("a");
			a.href = file.url;
			a.download = file.name.split('.')[0];
			document.body.appendChild(a);
			a.click(); // 点击下载
			document.body.removeChild(a); // 下载完成移除元素
		}
	}

	// 图片和文件类型上传成功之后的回调
	function imageBeforUploadSuccess(response:any, file:any, fileList:any, el:any) {
		console.log(response, file, fileList, el)
		if(response.code == 400)
		{
	
			ElMessage({message: response.msg,type: 'error'})
			for (let i = 0; i < formData.value[el].length; i++) {  
			    if (formData.value[el][i].uid === file.uid) {  
			        formData.value[el].splice(i, 1); // 从索引i开始移除一个元素  
			        break; // 找到后跳出循环  
			    }  
			}  
		}
		else
		{
			formData.value[el] = formData.value[el].map(item => {
				if (item.uid == file.uid) {
					const obj : any = {}
					obj.uid = file.uid
					obj.url = response.data.url
					obj.name = file.name
					return obj;
				}
				else {
					return item;
				}
			});
		}
		
		
		
		
	}

	function FileBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < feilType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (feilType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: feilType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: feilType.prompt,
				type: 'error',
			})
			return false;
		}
	}
	//图片预览
	function imglist(list: any) {
		console.log(list)
	    return list.map(item => item.url);
	}

	onMounted(() => {
		initLeiMu();
	});
</script>

<style lang="scss" scoped>
	.editorCont {
		min-height: 500px
	}

	.atcBox {
		background: #ffffff;
		width: 100%;
		margin: 0 auto;
		padding: 30px 40px;
		background: #fff;
		box-sizing: border-box;
	}


	.aletlCo {
		width: 100%;

		.artleTi {
			border-bottom: 1px solid #bfbfbf;
			padding: 8px 0;

			.artleTiH2 {
				font-size: 22px;
				color: #333333;
				text-align: center;
				line-height: 28px;
				font-weight: bold;
				margin-bottom: 8px;
			}

			.artleTiCo {
				display: flex;
				justify-content: center;
				flex-wrap: wrap;

				.artBs {
					margin-right: 20px;
				}

			}
		}

		.artleCo {
			line-height: 2;
			font-size: 16px;
			padding: 25px 0;

		}
	}

	.fujian {
		font-size: 14px;
		line-height: 30px;
	}

	.fujiana {
		background-size: 20px 25px;

		cursor: pointer;
		color: #2379f7;
	}

	.shBox {
		display: flex;
		justify-content: space-between;

		box-sizing: border-box;
		margin-top: 30px;
	}
</style>